package labox.innovation.gameserver.datatables;

import java.io.File;
import java.io.FileInputStream;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import javolution.util.FastMap;
import labox.innovation.config.Config;
import labox.innovation.gameserver.templates.chars.PlayerTemplate;

/**
 * 玩家角色模板管理表，装载和维护所有的玩家角色模板
 *
 * @version $Revision: 1.6.2.1.2.10 $ $Date: 2005/03/29 14:00:54 $
 */
public final class PlayerTemplateTable {

	private static final Logger _log = LoggerFactory.getLogger(PlayerTemplateTable.class.getName());

	protected Map<Integer, PlayerTemplate> _player = new FastMap<Integer, PlayerTemplate>();

	public static PlayerTemplateTable getInstance() {
		return SingletonHolder._instance;
	}

	private PlayerTemplateTable() {
	}

	public final void fromXML() {
		try {
			File f = new File(Config.DATAPACK_ROOT, "/Scene/playerTemplate.xml");
			FileInputStream fin = new FileInputStream(f);
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			DocumentBuilder builder = factory.newDocumentBuilder();
			Document document = builder.parse(fin);
			Element root;
			root = document.getDocumentElement();
			if (root.getTagName().compareTo("PlayerTemplates") != 0) {
				throw new Exception("Not a PlayerTemplates file!");
			}

			NodeList nl = root.getElementsByTagName("ActorClass");
			Element el;
			for (int i = -1; ++i < nl.getLength();) {
				el = (Element) nl.item(i);
				PlayerTemplate ct = new PlayerTemplate(el);
				getInstance()._player.put(ct._id, ct);
			}
			fin.close();
		} catch (Exception ex) {
			_log.error("CharTemplateTable: Error loading data.", ex);
		}
	}

	public PlayerTemplate getTemplate(int id) {
		return (PlayerTemplate) _player.get(id);
	}

	public final String getClassNameById(int classId) {
		PlayerTemplate pcTemplate = (PlayerTemplate) _player.get(classId);
		if (pcTemplate == null) {
			throw new IllegalArgumentException("No template for classId: " + classId);
		}
		return pcTemplate.className;
	}

	@SuppressWarnings("synthetic-access")
	private static class SingletonHolder {
		protected static final PlayerTemplateTable _instance = new PlayerTemplateTable();
	}
}
